package com.medic.client.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class CoreAction {
	
	private String TOKEN="client";
	
	@RequestMapping("/coreAction")
	@ResponseBody
	public String vaildate(@RequestParam( "signature" )String signature, 
			@RequestParam( "echostr" )String echostr,
			@RequestParam( "timestamp" )String timestamp,
			@RequestParam( "nonce" )String nonce)
			throws NoSuchAlgorithmException{
		
		ArrayList<String> list=new ArrayList<String>();
		list.add(TOKEN);
		list.add(nonce);
		list.add(timestamp);
		Collections.sort(list);
		String vaildate="";
		for(String s:list)
			vaildate += s;
		
		MessageDigest md = MessageDigest.getInstance("SHA-1");

		String sha1 = bytetoString(md.digest(vaildate.getBytes()));
		
		if(sha1.equals(signature)) return echostr;

		return "false";
	}
    
    public static String bytetoString(byte[] digest) {
        String str = "";
        String tempStr = "";
        
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            }
            else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }
}
